package com.oneandseven.dajia.service;

import com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisClient;
import com.azure.ai.formrecognizer.documentanalysis.models.AnalyzeResult;
import com.azure.ai.formrecognizer.documentanalysis.models.OperationResult;
import com.azure.core.util.polling.SyncPoller;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.oneandseven.dajia.bean.WorkReviewResult;
import com.oneandseven.dajia.constant.Prompts;
import com.oneandseven.dajia.openai.ChatCompletion;
import com.oneandseven.dajia.openai.ChatCompletionsRequest;
import com.oneandseven.dajia.openai.OpenAiClient;
import com.oneandseven.dajia.utils.FileConverter;
import com.oneandseven.dajia.utils.StrUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ThirdToolService {
    private static final Logger LOG = LoggerFactory.getLogger(ThirdToolService.class);

    @Autowired(required = false)
    private DocumentAnalysisClient documentAnalysisClient;

    @Autowired(required = false)
    private OpenAiClient openAiClient;

    @Autowired(required = false)
    private COSClient cosClient;

    @Value("${tencent.cos.bucket-name:#{null}}")
    private String tencentCloudBucketName;
//    @Autowired
//    public ThirdToolService(DocumentAnalysisClient documentAnalysisClient, OpenAiClient openAiClient, COSClient cosClient) {
//        this.documentAnalysisClient = documentAnalysisClient;
//        this.openAiClient = openAiClient;
//        this.cosClient = cosClient;
//
//    }

    /**
     * 上传文件
     */
    public String uploadWorkImage(long workId, long uid, MultipartFile file) throws Exception{
        String filename = file.getOriginalFilename();
        PutObjectRequest putObjectRequest = new PutObjectRequest(tencentCloudBucketName, filename, FileConverter.convertMultipartFileToFile(file));
        long st = System.currentTimeMillis();
        cosClient.putObject(putObjectRequest);
        String imageUrl = cosClient.getObjectUrl(tencentCloudBucketName, filename).toString();
        LOG.info("upload work image cost={}", (System.currentTimeMillis() - st));
        Map<String,String> reviewTask = new HashMap<>();
        return imageUrl;
    }

    /**
     * 把图片转成文字，会返回标题和内容，标题有可能为空
     * @param workImageUrl 学生仿写作文内容，图片格式，拍照和上传时用
     */
    public Map<String,String> ocrWork(String workImageUrl){
        SyncPoller<OperationResult, AnalyzeResult> analyzeOcrResult =
                documentAnalysisClient.beginAnalyzeDocumentFromUrl("prebuilt-read", workImageUrl);
        AnalyzeResult analyzeResult = analyzeOcrResult.getFinalResult();
        String originalContent = analyzeResult.getContent();
        float maxWidth = analyzeResult.getPages().get(0).getWidth();
        float firstLineLeftGap = analyzeResult.getPages().get(0).getLines().get(0).getBoundingPolygon().get(0).getX();
        String firstLineText = analyzeResult.getPages().get(0).getLines().get(0).getContent();
        int firstLineTextWordCount = StrUtil.countWords(firstLineText);
        String workTitle;
        String workContent;
        if( firstLineTextWordCount <= 4 && firstLineLeftGap > maxWidth*0.25){
            workTitle = firstLineText;
            workContent = originalContent.split("\n",2)[1];
        } else {
            workTitle = "";
            workContent = originalContent;
        }
        Map<String,String> ret = new HashMap<>();
        ret.put("workTitle", workTitle);
        ret.put("workContent", workContent);
        return ret;
    }

    /**
     * 老师改写学生提交的仿写作业
     */
    public WorkReviewResult rewriteWork(String studentContent) throws Exception{
        List<ChatCompletionsRequest.ChatRequestMessage> chatMessages = new ArrayList<>();
        chatMessages.add(new ChatCompletionsRequest.ChatRequestMessage("system", Prompts.CHINESE_REVIEW_PROMPT));
        chatMessages.add(new ChatCompletionsRequest.ChatRequestMessage("user", studentContent));
        ChatCompletion chatCompletions = openAiClient.getChatCompletion(
                new ChatCompletionsRequest(chatMessages)
                        .setModel("gpt-4-1106-preview")
                        .setMax_tokens(2048)
                        .setTemperature(0d)
                        .setResponse_format(new ChatCompletionsRequest.ResponseFormat("json_object")));
        String reviewContent = chatCompletions.getChoices().get(0).getMessage().getContent();
        return new JsonMapper().readValue(reviewContent, WorkReviewResult.class);
    }
}
